#pragma once
// 用于打包成功
#include "callback.h"
#include "eventloop.h"
#include "noncopyable.h"
#include <memory>
#include <unistd.h>
#include <atomic>
#include "inet_address.h"
#include "buffer.h"
class Channel;
class EventLoop;
class Socket;
class TimeStamp;

/**
 * TcpServer  => Acceptor 有一个新用户连接
 *   ==》 TcpConnection 设置回调  =》 Channel =》  Poller =》 Channel 的回调操作
 */
class TcpConnection: public noncopyable, public std::enable_shared_from_this<TcpConnection>{
public:
    enum StateE{
            kDisconnected,
            kConnecting,
            kConnected,
            kDisconnecting
        };
    TcpConnection(EventLoop* loop, 
            const std::string& name,
            int sockfd,
            const InetAddress& localAddr,
            const InetAddress& peerAddr);

    ~TcpConnection();

    EventLoop* getLoop() const {return loop_;};
    const std::string& name() const {return name_;}
    const InetAddress& localAddress() const{return localAddr_;}
    const InetAddress& peerAddress() const {return peerAddr_;}

    bool connected() const {return state_ == kConnected;}

    // 发送数据
    void sendInLoop(const void * message, int len);
    void shutdown();

 
    void setConnectionCallBack(const ConnectionCallBack& cb) {connectionCallBack_ = cb;}
    void setMessageCallBack(const MessageCallBack& cb) {messageCallBack_ = cb;}
    void setWriteCompleteCallBack(const WriteCompleteCallBack& cb) {writeCompleteCallBack_ = cb;}
    void setCloseCallBack(const CloseCallBack& cb) {closeCallBack_ = cb;}
    void setHighWaterMarkCallBack(const HighWaterMarkCallBack& cb) {highWaterMarkCallBack_ = cb;}

    // 连接建立
    void connectEstablished();
    // 连接销毁
    void connectDestoryed();

    void setState(StateE state) {state_ = state;}

    void send(const std::string& buf);
    void shutdownInLoop();
  

private:
    void handleRead(TimeStamp receiveTime);
    void handleWrite();
    void handleClose();
    void handleError();


    
    EventLoop* loop_;  // 记录这个TcpConnection 是在哪个Loop里面(SubLoop)
    const std::string name_;

    std::atomic_int state_;
    bool reading_;

    std::unique_ptr<Socket> socket_;
    std::unique_ptr<Channel> channel_;

    const InetAddress localAddr_;
    const InetAddress peerAddr_;

    ConnectionCallBack connectionCallBack_;    // 有新连接的回调
    MessageCallBack messageCallBack_;          // 有读写消息是的回调
    WriteCompleteCallBack writeCompleteCallBack_;     // 消息发送完成以后的回调
    HighWaterMarkCallBack highWaterMarkCallBack_;     // 消息发送完成以后的回调
    CloseCallBack closeCallBack_;

    size_t highWaterMark_;

    Buffer inputBuffer_;
    Buffer outputBuffer_;

};